﻿using System.Security.Cryptography;
using System.Text;

namespace AiQiuQuan.Sport.Core.Tool
{
    /// <summary>
    /// 加密解密类（AES）
    /// </summary>
    public class AESCryptography
    {
        /// <summary>
        /// 加密
        /// </summary>
        public static string Encrypt(string text, string key)
        {
            var sourceArray = Encoding.UTF8.GetBytes(text);

            var keyArray = Encoding.UTF8.GetBytes(key);
            var ivArray = new byte[16];
            Array.Copy(keyArray, ivArray, 16);

            var aes = Aes.Create();
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            aes.Key = keyArray;
            aes.IV = ivArray;
            var transform = aes.CreateEncryptor();
            return Convert.ToBase64String(transform.TransformFinalBlock(sourceArray, 0, sourceArray.Length));
        }

        /// <summary>
        /// 解密
        /// </summary>
        public static string Decrypt(string text, string key)
        {
            try
            {
                var encryptArray = Convert.FromBase64String(text);

                var keyArray = Encoding.UTF8.GetBytes(key);
                var ivArray = new byte[16];
                Array.Copy(keyArray, ivArray, 16);

                var aes = Aes.Create();
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                aes.Key = keyArray;
                aes.IV = ivArray;
                var transform = aes.CreateDecryptor();
                return Encoding.UTF8.GetString(transform.TransformFinalBlock(encryptArray, 0, encryptArray.Length));
            }
            catch (Exception)
            {
            }

            return null;
        }
    }
}
